<template>
  <div v-if="visible" class="padding flex direction-column overlay-page dark-alpha-block">
    <div class="overlay-top">
      <el-tooltip content="返回" placement="top">
        <el-button icon="el-icon-back" circle @click="close"></el-button>
      </el-tooltip>
      <span class="margin-left">监测点管理</span>
    </div>
    <div class="margin-top button-group">
      <el-button type="primary" @click="assignWorkShop">分配车间</el-button>
      <el-button type="danger" @click="freeWorkShop">释放车间</el-button>
    </div>
    <el-table
      v-loading="loading" class="table" :data="lists" height="100%"
      :header-cell-style="{
        color: 'white',
        backgroundColor: themeColor
      }"
      @selection-change="onSelectionChange"
    >
      <div slot="empty" class="empty-lists">
        <i class="i-custom:search"></i>
        <span class="empty-text">暂无数据</span>
      </div>
      <el-table-column type="selection"></el-table-column>
      <el-table-column v-for="column in columns" :key="column.prop" v-bind="column"></el-table-column>
      <el-table-column label="操作" prop="operate" align="center" width="160">
        <template #default="{ row }">
          <td-button icon="editor" title="编辑" @click="edit(row)"></td-button>
          <td-button
            icon="ashbin" title="删除"
            icon-style="color: var(--danger-color);border-color: var(--danger-color);"
            @click="del(row)"
          ></td-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination" layout="total,prev,pager,next"
      :hide-on-single-page="false" background
      :current-page.sync="pagination.pageNumber" :page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="getLists"
    ></el-pagination>
  </div>
</template>

<script>
import { selectIndicatorPageList, batchUpdateHierarchy, batchUnbundle } from '@/api/indicator'
import { selectPointList } from '@/api/point'
import TdButton from '@/components/td-button'

export default {
  name: 'monitor-points-manage',
  components: { TdButton },
  data () {
    return {
      visible: false,
      loading: false,
      lists: [],
      columns: [
        { label: 'ID', prop: 'id' },
        { label: '测点代码', prop: 'indicatorCode' },
        { label: '测点名称', prop: 'indicatorName' },
        { label: '能源折扣系数', prop: 'energyDiscountName' },
        { label: '测点范围', prop: 'indicatorScope' },
        { label: '测点类型', prop: 'typeName' },
        { label: '计量单位', prop: 'measuringUnit' },
      ],
      selection: [],
      pagination: {
        pageNumber: 1,
        pageSize: 20,
        total: 0,
      },
      pointCode: '',
      error: '',
    }
  },
  computed: {
    themeColor () {
      return this.$store.state.user.theme
    }
  },
  methods: {
    reload () {
      this.pagination.pageNumber = 1
      this.$nextTick(() => {
        this.getLists()
      })
    },
    open () {
      this.visible = true
      this.pagination.pageNumber = 1
      this.$nextTick(() => {
        this.getLists()
      })
    },
    close () {
      this.visible = false
      this.$emit('on-close')
    },
    getLists () {
      this.loading = true
      const { pageNumber, pageSize } = this.pagination
      return selectIndicatorPageList(pageNumber, pageSize).then(res => {
        if (res.code === 200) {
          res.data.records.forEach(v => {
            v.energyDiscountId = Number(v.energyDiscountId)
            v.energyUseId = Number(v.energyUseId)
            v.energyVarietiesTypeId = Number(v.energyVarietiesTypeId)
          })
          this.lists = res.data.records
          this.pagination.total = res.data.total
        }
      }).finally(() => {
        this.loading = false
      })
    },
    onSelectionChange (selection) {
      this.selection = selection
    },
    createWorkShopPicker (options) {
      const h = this.$createElement
      const vm = this
      const Picker = h(
        'el-select',
        {
          ref: 'work-shop-picker',
          class: 'width-100',
          props: {
            value: vm.pointCode,
          },
          on: {
            change (value) {
              vm.pointCode = value
              const picker = vm.$refs['work-shop-picker']
              picker.$parent.$el.querySelector('.picker-error').textContent = ''
              picker.value = value
            }
          },
        },
        [
          ...options.map(v => h('el-option', {
            props: {
              label: v.pointName,
              value: v.pointCode,
            }
          }))
        ]
      )
      const Error = h('p', {
        style: `
            color: red;
          `,
        class: 'picker-error'
      }, vm.error || '')
      return h('div', [Picker, Error])
    },
    getWorkShopOptions () {
      return selectPointList().then(res => {
        if (res.code === 200) {
          const data = res.data
          if (Array.isArray(data) && data[0]) {
            return data[0].children
          }
        }
      })
    },
    assignWorkShop () {
      const selection = this.selection
      if (selection.length < 1) {
        return this.$message.error('请至少选择一条数据进行操作')
      }
      const ids = selection.map(v => v.id)
      const vm = this
      this.getWorkShopOptions().then(options => {
        this.$msgbox({
          title: '选择要分配的车间',
          message: this.createWorkShopPicker(options),
          beforeClose (action, instance, done) {
            if (action === 'confirm') {
              if (vm.pointCode) {
                batchUpdateHierarchy(vm.pointCode, ids).then(res => {
                  if (res.code === 200) {
                    done()
                    vm.reload()
                  }
                })
              } else {
                vm.error = '请选择车间'
                instance.$el.querySelector('.picker-error').textContent = vm.error
              }
            } else {
              done()
            }
          },
        }).catch(() => {})
      })
    },
    edit (row) {
      this.$emit('edit-row', row)
    },
    del (row) {
      this.$emit('del-row', row)
    },
    freeWorkShop () {
      const selection = this.selection
      if (selection.length < 1) {
        return this.$message.error('请至少选择一条数据进行操作')
      }
      const ids = selection.map(v => v.id)
      batchUnbundle(ids).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功')
          this.reload()
        }
      })
    },
  },
}
</script>

<style scoped>

</style>
